<template>
  <XLayoutMain>
    <div class="g-content">

      <div class="flex" style="margin-bottom: 10px; width: 100%">
        <n-space align="center">
          <x-button type="primary" @click="handleAdd('create', {})">添加广告</x-button>
          <n-text>添加广告后所有账户将全部新增广告</n-text>
        </n-space>
      </div>
      <n-tabs
        v-if="tabs[0]"
        v-model:value="accountCode"
        type="card"
        closable
        @close="handleClose"
        @update:value="immediate = true"
      >
        <n-tab-pane v-for="item in tabs" :key="item" :name="item" :tab="`账户ID: ${item}`" />
      </n-tabs>
      <x-data-table
        v-if="accountCode && tabs.length > 0"
        ref="tableRef"
        v-model:immediate="immediate"
        :params="paginationParams"
        :columns="columns"
        :render-cell="renderCell"
        :row-key="(row) => row.adgroupId"
        :scoll-x="1600"
        :toolbar="false"
        :page-sizes="[20]"
        max-height="calc(100vh - 320px)"
        @change="getTableData"
      />
      <!-- 批量上传其他参数-->
      <div v-if="tableData.length > 0 && accountCode" class="m-batch-form">
        <x-form ref="formRef" v-model:model="form" :rules="rules" label-placement="left" label-width="180">
          <n-form-item label="每条广告上传数量" path="num">
            <n-input-number
              v-model:value="form.num"
              size="small"
              controls-position="right"
              :min="1"
              :max="50"
              :precision="0"
            />
            <n-text style="margin-left: 10px">条</n-text>
          </n-form-item>
          <n-form-item label="计划、广告关闭类型" path="closeType">
            <n-radio-group v-model:value="form.closeType">
              <n-radio :label="'关闭广告'" :value="1" style="margin-right: 10px" />
              <n-radio :value="2" style="margin-right: 10px">
                <div style="position: relative">
                  <n-text>开启广告</n-text>
                  <n-text
                    v-show="form.closeType === 2"
                    style="position: absolute; bottom: -30px; left: 0; width: 200px"
                    type="error"
                    depth="3"
                  >
                    广告审核通过自动进入投放
                  </n-text>
                </div>
              </n-radio>
              <n-radio :label="'上传时开启，审核完成后关闭广告'" :value="3" />
            </n-radio-group>
          </n-form-item>
          <n-form-item label="上传顺序" path="order">
            <n-radio-group v-model:value="form.order">
              <n-radio :value="0" style="margin-right: 10px">
                <div style="position: relative">
                  <n-text>顺序上传</n-text>
                  <n-tag v-show="form.order === 0" style="position: absolute; bottom: -40px; left: 0" type="success">
                    按1234....1234...的顺序上传
                  </n-tag>
                </div>
              </n-radio>
              <n-radio :value="1" style="margin-right: 10px">
                <div style="position: relative">
                  <n-text>循环上传</n-text>
                  <n-tag v-show="form.order === 1" style="position: absolute; bottom: -40px; left: 0" type="success">
                    按1111....2222...的顺序上传
                  </n-tag>
                </div>
              </n-radio>
            </n-radio-group>
          </n-form-item>
          <n-form-item>
            <div style="margin: 0 auto">
              <n-space vertical align="center">
                <x-button :loading="updateLoading" :disabled="totalNum === 0" type="primary" @click="handleUpload"
                  >上传广告</x-button
                >
                <n-text>系统已为您自动保存内容</n-text>
              </n-space>
            </div>
          </n-form-item>
        </x-form>
      </div>
    </div>
    <PreviewModal v-if="previewData.show" :modal-data="previewData" />
    <UploadCallbackModal v-if="callbackModal.show" :modal-data="callbackModal" @success="immediate = true" />
  </XLayoutMain>
</template>

<script setup lang="ts">
  import { XLayoutMain, XDataTable, XButton, XForm } from '@/components'
  import { useRoute, useRouter } from 'vue-router'
  import { computed, h, onMounted, reactive, ref, VNode } from 'vue'
  import {
    NSpace,
    NTabs,
    NTabPane,
    NImage,
    NInputNumber,
    useMessage,
    NText,
    NFormItem,
    NRadioGroup,
    NTag,
    NRadio,
    useNotification,
    NPopconfirm,
    useDialog
  } from 'naive-ui'
  import { useStore } from '@/store'
  import UploadCallbackModal from '@/views/advertising/ads/list/components/UploadCallbackModal.vue'
  import ImgDefault from '@/assets/images/img-default.png'
  import { adgroupAccountCodeList } from '@/api/intelligent'
  import PreviewModal from '@/views/advertising/ads/list/components/PreviewModal.vue';

  const store = useStore()
  const message = useMessage()
  const notify = useNotification()
  const router = useRouter()
  const route = useRoute()
  const tabs = ref([])
  const batchId = route.query.batchId
  const previewData = ref({
    show: false,
    currow: {}
  })
  const form = ref({
    num: 10,
    closeType: 1,
    pageSize: 100,
    order: 0,
    batchId: batchId
  })
  const formRef = ref()
  const rules = reactive({
    num: {
      type: 'number',
      required: true,
      trigger: ['input', 'blur'],
      message: '请填写每条广告上传数量'
    },
    closeType: {
      type: 'number',
      required: true,
      trigger: ['input', 'blur'],
      message: '请选择关闭类型'
    },
    order: {
      type: 'number',
      required: true,
      trigger: ['input', 'blur'],
      message: '请选择上传顺序'
    }
  })
  const callbackModal = ref({
    show: false
  })
  const dialog = useDialog()
  const updateLoading = ref(false)
  const totalNum = ref(0)
  const tableRef = ref()
  const immediate = ref(false)
  const tableData = ref([])
  const accountCode = ref(null)
  const paginationParams = computed(() => {
    const params = {
      batchId: batchId,
      pageSize: 1000,
      accountCode: accountCode.value
    }
    return {
      actions: 'intelligent/getAdsManageList',
      data: params
    }
  })
  const columns = reactive([
    {
      title: '序号',
      key: 'key',
      width: 80,
      render: (_: any, index: number) => {
        return tableData.value.length - index
      }
    },
    {
      title: '广告名称',
      key: 'name',
      width: 220,
      render(row: any): VNode {
        // return h(NInput, {
        //   type: 'textarea',
        //   value: row.name,
        //   onUpdateValue(v) {
        //     row.name = v
        //   },
        //   onFocus: () => onNameValFocus(row.name),
        //   onBlur: () => handleName(row)
        // })
        return row.adgroupName
      }
    },
    {
      title: '创意素材',
      key: 'mediaUrlList',
      width: 200,
      render(row: any): VNode {
        // return h(NImage, { previewedImgProps: { style: {} }, src: row.mediaUrlList?.[0].previewUrl || '-' })
        return h(
          'div',
          { style: { position: 'relative', maxHeight: '120px' }, onClick: () => handlePreviewData(row) },
          [
            row.mediaUrlList?.[0].urlList?.[0]?.type === 2
              ? h('video', {
                  controls: true,
                  objectFit: 'fill',
                  controlsList: 'nodownload',
                  height: 120,
                  src: row.mediaUrlList?.[0].urlList?.[0]?.url || '-'
                })
              : h(NImage, {
                  previewDisabled: true,
                  previewedImgProps: { style: {} },
                  objectFit: 'fill',
                  height: 120,
                  src:
                    row.mediaUrlList?.[0].urlList?.[0]?.url ||
                    'https://alicdn.itaored.com/test/feima-uploaded/images/a8/1f/a81f32e133c829e8e3cdfe1784f8a4ad.png?x-oss-process=image/resize,w_150/quality,q_94/format,webp',
                  alt: '图片加载失败',
                  fallbackSrc:
                    'https://alicdn.itaored.com/test/feima-uploaded/images/a8/1f/a81f32e133c829e8e3cdfe1784f8a4ad.png?x-oss-process=image/resize,w_150/quality,q_94/format,webp'
                })
          ]
        )
      }
    },
    {
      title: '投放日期',
      key: 'addTime',
      width: 200,
      render(row: any): VNode {
        return h(NSpace, { align: 'center' }, () => [
          h(NSpace, { vertical: true, align: 'center' }, () => [
            row.releaseTimeType === 1
              ? [h(NText, {}, () => row.releaseBeginDate), h(NText, {}, () => '全天')]
              : row.releaseBeginTime + '-' + row.releaseEndTime
          ])
        ])
      }
    },
    {
      title: '操作',
      width: 180,
      fixed: 'right',
      render(row: any) {
        return h(NSpace, {}, () => [
          h(XButton, { type: 'primary', text: true, onClick: () => handleAdd('copy', row) }, () => '复制'),
          h(XButton, { type: 'primary', text: true, onClick: () => handleAdd('edit', row) }, () => '编辑'),
          h(
            NPopconfirm,
            { onPositiveClick: () => handleAdd('delete', row) },
            {
              default: () => '是否删除？',
              trigger: () => h(XButton, { type: 'primary', text: true }, () => '删除')
            }
          )
        ])
      }
    }
  ])
  onMounted(() => {
    getAdgroupAccountCodeList()
  })

  // 获取列表数据
  async function getAdgroupAccountCodeList() {
    const { data } = await store.dispatch('intelligent/adgroupAccountCodeList', {
      batchId: batchId
    })
    tabs.value = data
    if (data.length > 0) {
      accountCode.value = data[0]
      immediate.value = true
    }
  }
  // 删除账户
  async function handleClose(name: number) {
    dialog.create({
      title: '提示',
      content: '是否确认删除！',
      positiveText: '删除',
      negativeText: '取消',
      onPositiveClick: async () => {
        const { code } = await store.dispatch('intelligent/adgroupBatchDelete', {
          batchId: batchId,
          accountCode: accountCode.value
        })
        if (code !== '200') {
          return
        } else {
          const index = tabs.value.findIndex((v) => name === v)
          tabs.value.splice(index, 1)
          if (accountCode.value === name) {
            accountCode.value = tabs.value[index]
          }
          window.location.reload()
        }
      }
    })
  }
  function renderCell(val: string | number | null) {
    if (val === null) {
      return '-'
    }
    return val
  }
  function getTableData(res: any) {
    tableData.value = res.data
    totalNum.value = res.data.length || 0
  }
  // 添加广告
  async function handleAdd(type: string, row: any) {
    if (type === 'create') {
      router.push({
        name: 'AdsCreate',
        query: {
          // accountCode: tabs.value,
          type: 'create',
          batchId
        }
      })
    } else if (type === 'copy') {
      store
        .dispatch('intelligent/adsManageCopy', {
          adgroupIdList: [row.adgroupId],
          batchId: batchId
        })
        .then(() => {
          immediate.value = true
        })
        .catch(() => {
          // message.warning('复制失败！')
        })
    } else if (type === 'edit') {
      router.push({
        name: 'AdsCreate',
        query: {
          accountCode: row.accountCode,
          type: 'edit',
          adgroupId: row.adgroupId,
          id: row.id
        }
      })
    } else if (type === 'delete') {
      store
        .dispatch('intelligent/adsManageRemove', {
          adgroupId: row.adgroupId
        })
        .then(() => {
          immediate.value = true
          window.location.reload()
        })
        .catch(() => {
          // message.warning('删除失败！')
        })
    }
  }
  // 查看素材详情
  function handlePreviewData(row: any) {
    previewData.value = {
      show: true,
      currow: row
    }
  }
  // 上传广告
  function handleUpload() {
    updateLoading.value = true
    const params = {
      batchId: batchId,
      num: form.value.num,
      closeType: form.value.closeType,
      order: form.value.order
    }
    store
      .dispatch('intelligent/uploadAdgroup', params)
      .then((res) => {
        updateLoading.value = true
        immediate.value = true
        callbackModal.value.show = true
      })
      .catch(() => {
        updateLoading.value = false
      })
  }
  // 获取第一条上传情况
  function showProgress() {
    store
      .dispatch('intelligent/adsProgress', {
        accountCode: accountCode,
        num: form.value.num,
        total: form.value.num,
        batchId: batchId
      })
      .then((res) => {
        const data = res.data
        if (data.firstStatus === 1) {
          updateLoading.value = false
          immediate.value = true
          callbackModal.value.show = true
        } else {
          if (data.errorInfo) {
            notify.error({
              title: `${data.errorInfo.name || ''}`,
              content: data.errorInfo.msg,
              duration: 0
            })
            updateLoading.value = false
          } else {
            setTimeout(() => {
              showProgress()
            }, 3000)
          }
        }
      })
      .catch((e) => {
        if (e !== '连接服务器超时，请重试!') {
          updateLoading.value = false
          immediate.value = true
        }
      })
  }
</script>

<style scoped lang="scss">
  @import 'src/assets/styles/var';
  .m-batch-form {
    padding: 10px 0;
  }
  .tips {
    text-align: center;
    margin-top: 20px;
  }
  .title {
    padding-bottom: 20px;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: bold;
    color: #646464;
    border-bottom: 1px solid #eaecf0;

    .advertiser-name {
      margin-right: 20px;
    }
  }

  .date {
    margin-right: 10px;
  }

  .btn-row {
    margin-bottom: 10px;
    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
  .account-more {
    display: flex;
    flex-flow: column;
    width: 100%;
    .item {
      min-height: 34px;
      align-items: center;
      display: flex;
      .ul {
        flex: 1;
        display: flex;
        flex-flow: row wrap;
        .li {
          display: flex;
          align-items: center;
          box-sizing: border-box;
          margin-right: 10px;
          margin-bottom: 10px;
          border: 1px solid $primaryColor;
          border-radius: 50px;
          padding: 0 8px;
        }
      }
      .del-all {
        color: $primaryColor;
        cursor: pointer;
      }
    }
  }
</style>
